import { useState, useEffect, useRef } from 'react';

export function useTypewriterEffect(text: string, speed: number) {
  const [displayedText, setDisplayedText] = useState('');
  const indexRef = useRef(0); // 持久化索引

  useEffect(() => {
    if (speed <= 0 || text.length === 0) return; // 无效参数直接返回

    setDisplayedText(''); // 重置文本
    indexRef.current = 0; // 重置索引

    const intervalId = setInterval(() => {
      if (indexRef.current < text.length) {
        // 安全访问当前字符并更新状态
        const nextChar = text[indexRef.current];
        if (nextChar !== undefined) {
          setDisplayedText((prev) => prev + nextChar);
          indexRef.current += 1;
        }
      } else {
        clearInterval(intervalId); // 当完成时清除 interval
      }
    }, speed);

    return () => clearInterval(intervalId);
  }, [text, speed]);

  return displayedText;
}
